package com.sinotrans.gateway.config.security;

import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import com.google.common.net.MediaType;
import com.google.gson.Gson;
import com.sinotrans.common.constant.Constant;
import com.sinotrans.common.rest.RestEntity;
import com.sinotrans.common.security.AuthEntity;
import com.sinotrans.common.security.AuthUtils;
import com.sinotrans.common.security.DigestSignature;
import com.sinotrans.common.security.auth.OAuthUtils;
import com.sinotrans.common.util.Utils;
import com.sinotrans.gateway.service.JwtService;
import com.sinotrans.gateway.service.SecurityService;

import reactor.core.publisher.Mono;

/**
 * 将JWT转化成用户信息的全局过滤器
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

	private static Logger LOGGER = LoggerFactory.getLogger(AuthGlobalFilter.class);

	@Autowired
	private JwtService jwtService;

	@Autowired
	private SecurityService securityService;

	@Autowired
	private DigestSignature digestSignature;

	protected Gson gson = Utils.getGson();

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		AuthEntity authEntity = null;
		//
		RequestPath path = exchange.getRequest().getPath();
		boolean isIgnoreUrl = securityService.isAuthIgnoreUrl(path.value());
		if (isIgnoreUrl) {
			authEntity = new AuthEntity();
			authEntity.setIsd(OAuthUtils.True);
		} else {
			try {
				String bearerToken = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
				if (StringUtils.isEmpty(bearerToken)) {
					return unauthorized(exchange, "Authorization is empty");
				}
				String token = bearerToken.replace(Constant.AUTHORIZATION_BEARER, Constant.EMPTY_STRING).trim();
				authEntity = jwtService.decodeVerifyAccesstoken(token);
			} catch (Exception e) {
				LOGGER.error("decode verify access token error.", e);
				return unauthorized(exchange, e.getMessage());
			}
		}
		try {
			authEntity.setChn(AuthUtils.GATEWAY);
			String authinfo = digestSignature.encode(authEntity);
			ServerHttpRequest request = exchange.getRequest().mutate().header(AuthUtils.authorize, authinfo).build();
			exchange = exchange.mutate().request(request).build();
		} catch (Exception e) {
			LOGGER.error("digestSignature error.", e);
		}
		return chain.filter(exchange);
	}

	private Mono<Void> unauthorized(ServerWebExchange exchange, String msg) {
		ServerHttpResponse response = exchange.getResponse();
		RestEntity<String> rest = new RestEntity<String>();
		rest.setSuccess(false);
		rest.setErrcode(String.valueOf(HttpStatus.UNAUTHORIZED.value()));
		rest.setErrmsg(msg);
		byte[] bits = gson.toJson(rest).getBytes(StandardCharsets.UTF_8);
		DataBuffer buffer = response.bufferFactory().wrap(bits);
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
		return response.writeWith(Mono.just(buffer));
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
